package com.winning.ds.common.util;

import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @ClassName DbUtils
 * @Description TODO
 * @Author WJX
 * @Date 2019/8/15 14:06
 **/
public class DbConnectUtils {

    /**
     * oracle 的驱动名称
     */
    private final static String ORACLE_DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";

    /**
     * sqlserver 的驱动名称
     */
    private final static String SQLSERVER_DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";


    /**
     * mysql 的驱动名称
     */
    private final static String MYSQL_DRIVER_NAME = "com.mysql.jdbc.Driver";

    /**
     * 端口号
     */
    private static String DB_PORT;



    private static DbConnectUtils instance;

    /**
     * 获取到实例
     * @return
     */
    public static DbConnectUtils getInstance() {
        if (null == instance) {
            instance = new DbConnectUtils();
        }
        return instance;
    }

    /**
     * 连接 数据库
     * @param jdbcurl
     * @param username
     * @param password
     * @return
     */
    public Connection initDbConnect(String jdbcurl, String username, String password,String dbtype) throws SQLException, ClassNotFoundException {
        Connection conn = null;
        String drvierName = getDriverName(dbtype);
        if(StringUtils.isBlank(jdbcurl)){
            return null;
        }
        Class.forName(drvierName);
        //连接数据库
        conn = DriverManager.getConnection(jdbcurl, username, password);
        return conn;
    }

    /**
     *@描述 根据数据源类型判断驱动名称
     *@参数
     *@返回值
     *@创建人  wujiaxing
     *@创建时间  2019/8/15
     */
    public String getDriverName(String dbtype){
        String driverName = "";
        if(StringUtils.equalsIgnoreCase(dbtype,"ORACLE")){
            driverName = ORACLE_DRIVER_NAME;
        }else if(StringUtils.equalsIgnoreCase(dbtype,"SQLSERVER")){
            driverName = SQLSERVER_DRIVER_NAME;
        }else if(StringUtils.equalsIgnoreCase(dbtype,"MYSQL")){
            driverName = MYSQL_DRIVER_NAME;
        }
        return driverName;
    }

    /**
     * 获取到数据库连接url
     * @param dbtype
     * @param dbip
     * @param instancename
     * @return
     */
    public String getConnectUrl(String dbtype,String dbip,String instancename){
        String jdbcurl = "";
        if(StringUtils.equalsIgnoreCase(dbtype,"ORACLE")){
            //jdbcurl =  "jdbc:oracle:thin:@//" + dbip + ":1521/" + instancename;
            jdbcurl =  "jdbc:oracle:thin:@//" + dbip + ":1521/" + instancename;
        }else if(StringUtils.equalsIgnoreCase(dbtype,"SQLSERVER")){
            jdbcurl = "jdbc:sqlserver://" + dbip + ";DatabaseName=" + instancename;
        }
        return jdbcurl;
    }

}
